<?php

namespace App\Http\Models\Admin;

use App\Http\Controllers\Admin\Common;

class Department extends Base
{
    protected $table="department";

	/**
	 * [获取拥有数据权限的部门]
	 * @param $uid user_id
	 */
	public function getDataAuthDeparts($uid) {
		$user = User::where('id',$uid)->first()->toArray();
		switch ($user['data_auth_type']) {
			case '0': # self
				$departs = $this::where('id',$user['depart_id'])->get()->toArray();
				break;
			case '1': # all
				$departs = $this::get()->toArray();
				break;
			case '2': # 本部门 及 直属子集
				$departs = $this::where('pid',$user['depart_id'])->get()->toArray();
				$departs[] = $this::where('id',$user['depart_id'])->first()->toArray();
				break;
			case '3': # 本部门 及 所有子集
				$departs = $this->getSonsByPid($user['depart_id']);
				$departs[] = $this::where('id',$user['depart_id'])->first()->toArray();
				break;
			case '4': # 所有同级部门(包含自己)
				$pid = $this::where('id',$user['depart_id'])->value('pid');
				$departs = $this::where('pid',$pid)->get()->toArray();
				break;
			case '5': # 所有同级部门 和 直属子集
				$pid = $this::where('id',$user['depart_id'])->value('pid');
				$departs_1 = $this::where('pid',$pid)->get()->toArray();
				$departs_2 = $this::where('pid',$user['depart_id'])->get()->toArray();
				$departs = [];
				foreach($departs_1 as $d1){
					$departs[] = $d1;
				}
				foreach($departs_2 as $d2){
					$departs[] = $d2;
				}
				break;
			case '6': # 所有同级部门 和 所有所属子集
				$pid = $this::where('id',$user['depart_id'])->value('pid');
				$departs_1 = $this::where('pid',$pid)->get()->toArray();
				$departs_2 = $this->getSonsByPid($user['depart_id']);
				$departs = [];
				foreach($departs_1 as $d1){
					$departs[] = $d1;
				}
				foreach($departs_2 as $d2){
					$departs[] = $d2;
				}
				break;
		}
		return $departs;
	}

	/**
     * [获取所有子部门ID]
     */
    public function getSonsByPid($id,$is_2d=true){
        $arr = [];
        $lower = $this::where('pid',$id)->get()->toArray();
        foreach($lower as $k => $v){
            if($v){
                array_push($arr,$v);
                array_push($arr,$this->getSonsByPid($v['id']));
            }
        }
        if($is_2d){
            $arr = Common::Array_3dTo2d($arr);
        }
        $arr = array_merge(array_filter($arr));
        return $arr;
    }


}
